package com.shop.shoppingmall.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shoppingmall.dao.ShCheckDao;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.entity.ShCheck;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.service.ShCheckService;
import com.shop.shoppingmall.util.*;
import com.shop.shoppingmall.util.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 实名认证(ShCheck)表服务实现类
 *
 * @author makejava
 * @since 2020-09-05 14:21:42
 */
@Service("shCheckService")
@Slf4j
@Transactional
public class ShCheckServiceImpl implements ShCheckService {
    @Resource
    private ShCheckDao shCheckDao;
    @Resource
    private ShUserDao shUserDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShCheck queryById(String id) {
        return this.shCheckDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<ShCheck> queryAllByLimit(int offset, int limit) {
        return this.shCheckDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param shCheck 实例对象
     * @return 实例对象
     */
    @Override
    public ShCheck insert(ShCheck shCheck) {
        this.shCheckDao.insert(shCheck);
        return shCheck;
    }

    /**
     * 修改数据
     *
     * @param shCheck 实例对象
     * @return 实例对象
     */
    @Override
    public ShCheck update(ShCheck shCheck) {
        this.shCheckDao.update(shCheck);
        return this.queryById(shCheck.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shCheckDao.deleteById(id) > 0;
    }

    /**
     * 用户进行实名认证
     * userId为用户表中的id
     *
     * @param
     * @param
     * @param
     * @return
     */
    @Override
    public Result checkPerson(HttpServletRequest request ,MultipartFile imgFile) {
        try {
            String name1 = JwtUtil.getUserNameByToken(request);
            ShUser shUser = shUserDao.selectLoginName(name1);
            if(shUser == null || name1 == null){
                return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
            }
            String fname = PhotoUtil.memoryPhoto(imgFile);
            //获取token
            TokenUtil tokenUtil = new TokenUtil();
            String token = tokenUtil.token();
            // 请求url
            String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
            // 本地文件路径
//            String filePath = "E:\\img/"+fname;
            byte[] imgData = FileUtil.readFileByBytes(fname);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "id_card_side=" + "front" + "&image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = token;
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            Map map = new ObjectMapper().readValue(result, Map.class);
            Map words_result = (Map) map.get("words_result");
            ShCheck shChecks = shCheckDao.queryById(shUser.getId());
            if (shChecks == null) {
                //2.获取身份证的名字
                String name = ((Map) words_result.get("姓名")).get("words") + "";
                //3.获取身份号，
                String personId = ((Map) words_result.get("公民身份号码")).get("words") + "";
                //4.获取性别
                String sex = ((Map) words_result.get("性别")).get("words") + "";
                //5.获取出生日期
                String birthday = ((Map) words_result.get("出生")).get("words") + "";
                //校验身份证号
                ShCheck check = shCheckDao.selectShCheckByCheckNum(personId);
                if (check != null) {
                    return Result.error("该身份证已经被实名");
                }
                ShCheck shCheck = new ShCheck();
                shCheck.setId(UUIDGenerator.generate());
                shCheck.setCheckName(name);
                shCheck.setCheckNum(personId);
                shCheck.setCheckSex(sex);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Date parse = sdf.parse(birthday);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String format = simpleDateFormat.format(parse);
                shCheck.setCheckBirthday(format);
                shCheck.setUserId(shUser.getId());
                //修改用户信息
                ShUser shUser1 = new ShUser();
                shUser1.setId(shUser.getId());
                shUser1.setRealName(name);
                shUser1.setBirthday(format);
                shUser1.setSex(sex);
                shUser1.setCheckState("1");
                if ("normal".equals(map.get("image_status"))) {
                    //正常返回的数据，信息没有错误
                    //插入身份证的信息到数据库
                    shCheckDao.insert(shCheck);
                    shUserDao.update(shUser1);
                    return Result.ok("实名认证成功");
                } else {
                    return Result.ok("身份证图片异常");
                }
            } else {
                return Result.error("该用户已经实名");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误");
        }
    }

    @Override
    public Result checkReal(HttpServletRequest request,String idCard ,String name){
        String name1 = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name1);
        if(shUser == null || name1 == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        System.out.println(idCard+name);
        String json = RealUtil.market1(idCard,name);
        System.out.println(json);
        JSONObject jsonObject = JSONObject.fromObject(json);
        log.info("用户id"+shUser.getId()+"实名信息返回"+jsonObject);
        String status = jsonObject.get("status").toString();
        if(status == null){
            return Result.error(""+jsonObject);
        }
        if(status.equals("01")){
            String checkNum = jsonObject.get("idCard").toString();
            String checkName = jsonObject.get("name").toString();
            String checkSex = jsonObject.get("sex").toString();
            String checkBirthday = jsonObject.get("birthday").toString();
            //添加实名记录
            ShCheck shCheck = new ShCheck();
            shCheck.setId(UUIDGenerator.generate());
            shCheck.setCheckName(checkName);
            shCheck.setCheckNum(checkNum);
            shCheck.setCheckSex(checkSex);
            shCheck.setCheckBirthday(checkBirthday);
            shCheck.setUserId(shUser.getId());
            shCheckDao.insert(shCheck);
            //修改用户信息
            shUser.setRealName(checkName);
            shUser.setBirthday(checkBirthday);
            shUser.setCheckState("1");
            shUserDao.update(shUser);
            return Result.ok("实名认证成功");
        }
        return Result.error("实名认证不通过!!");
    }
    /**
     * 根据userIdC查询实名认证的信息
     * @param
     * @return
     */
    @Override
    public Result selectShCheckByUserId(HttpServletRequest request) {
        String nameByToken = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(nameByToken);
        if(shUser == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        String userId = shUser.getId();
        ShCheck shCheck = shCheckDao.selectShCheckByUserId(userId);
        if(shCheck == null){
            return Result.error("暂时还没有相关信息，请先进行实名认证");
        }
        return Result.ok(shCheck);
    }
}
